  import Vue from 'vue'
  import Vuex from 'vuex'
  import getters from "./getters";

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: []
  },
  getters,
  mutations: {
    addCounter(state, payload) {
      payload.count++
    },
    addToCart(state,payload){
      payload.checked = true
      state.cartList.push(payload)
    },

  },
  actions: {
    addCart(context,payload) {
      // let oldProduct = null;
      // for(let item in state.cartList){
      //   if(item.iid === payload.iid){
      //     oldProduct = item
      //   }
      // }
     return new Promise((resolve, reject)=>{

       let oldProduct = context.state.cartList.find(item =>item.iid === payload.iid)
       if(oldProduct){
         // oldProduct.count +=1
         context.commit('addCounter',oldProduct)
         resolve('当前的商品+1')
       }else {
         payload.count = 1
         // context.state.cartList.push(payload)
         context.commit('addToCart',payload)
         resolve('添加新的商品')
       }
     })

    }
  }
})
